/*
 Basic ESP8266 MQTT example
 This sketch demonstrates the capabilities of the pubsub library in combination
 with the ESP8266 board/library.
 It connects to an MQTT server then:
  - publishes "hello world" to the topic "outTopic" every two seconds
  - subscribes to the topic "inTopic", printing out any messages
    it receives. NB - it assumes the received payloads are strings not binary
  - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
    else switch it off
 It will reconnect to the server if the connection is lost using a blocking
 reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
 achieve the same result without blocking the main loop.
 To install the ESP8266 board, (using Arduino 1.6.4+):
  - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
       http://arduino.esp8266.com/stable/package_esp8266com_index.json
  - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  - Select your ESP8266 in "Tools -> Board"
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h> 
#include <DHT.h>//定义库的头文件

#define DHTTYPE DHT12//温湿度传感器型号
#define DHT12_PIN 2//温湿度检测引脚                        
#define SOILHUM_PIN 0//土壤湿度检测引脚，模拟引脚 A0
#define LED 16//土壤湿度检测引脚，模拟引脚 A0

//服务参数
const char* ssid = "ChinaNet-yLJb";
const char* password = "nurmapz5";


//mqtt服务地址
const char* mqtt_server = "ip";
const char *mqtt_username = "";
const char *mqtt_password = "";
const char *s_topic = "v1/devices/me/rpc/hardware";
const char *p_topic = "v1/devices/telemetry";
WiFiClient espClient;
PubSubClient client(espClient);
//消息
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE	(50)
char msg[MSG_BUFFER_SIZE];
DHT dht(DHT12_PIN,DHTTYPE);//实例化

//初始化
void setup() {
  // BUILTIN_LED pin 输出
  pinMode(LED, OUTPUT);
  //初始化引脚（温湿度）
  pinMode(DHT12_PIN, INPUT);  
  //串口波特率
  Serial.begin(115200);  
  //初始化wifi，以及mq连接
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  //client.subscribe(s_topic);
}

//连接WiFi
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  randomSeed(micros());
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

//mq消息回调
void callback(char* topic, byte* payload, unsigned int length) {
  DynamicJsonDocument doc(1024);
  deserializeJson(doc, payload);
  JsonObject jsonObj = doc.as<JsonObject>();
  JsonObject params =jsonObj["params"];
  if(params["WaterOutletSwitch"] == 0){
    digitalWrite(LED, LOW);  
    Serial.println("LED-OFF");
  }
  if(params["WaterOutletSwitch"] == 1){
    digitalWrite(LED, HIGH); 
    Serial.println("LED-ON");
  }
  // Serial.print("Message arrived [");
  // Serial.print(topic);
  // Serial.print("] ");
}

//连接mq服务
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("connected s_topic");
      // Once connected, publish an announcement...
      client.publish(p_topic, "hello world");
      // ... and resubscribe
      client.subscribe(s_topic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
//硬件温湿度采集，发布
void dht11(){
  int tem =0;
  int hum;
  //读取温湿度数据
  dht.begin();
  tem=dht.readTemperature();
  hum=dht.readHumidity();
  int soilHum = soil_hum();
  //封装json对象
  DynamicJsonDocument data(256);
  data["temperature"]=22;
  data["humidity"]=22;
  data["soilHum"]=soilHum;
  char json_string[256];
  serializeJson(data,json_string);
  Serial.println(json_string);
  //发布数据
  client.publish(p_topic, json_string);
  Serial.print("\n");
}
//土壤湿度
int soil_hum(){
  int temp = 100 - analogRead(SOILHUM_PIN)/10.24;//模拟数据读取（A0脚输入的数据）
  Serial.println(temp);
  //temp = 50;
  return temp;
}

//主函数
void loop() {
  //客户端连接mqtt
  if (!client.connected()) {
     reconnect();
     } 
  client.loop();
  lastMsg++;
  if (lastMsg > 200000) {
    lastMsg=0;
    //采集土壤湿度数据,发布
    dht11();
  }
  
}

